import { createRouter, createWebHistory } from "vue-router";
// import HomeView from "../views/HomeView.vue";
import BasicLayout from "@/layout/BasicLayout";
import Login from "@/views/Login.vue";

const routes = [
  // {
  //   path: "/",
  //   name: "home",
  //   component: HomeView,
  // },
  // {
  //   path: "/about",
  //   name: "about",
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () =>
  //     import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
  // },
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  {
    path: "/",
    name: "BasicLayout",
    component: BasicLayout,
    children: [
      {
        path: "/search",
        name: "SearchPage",
        component: () =>
          import(/* webpackChunkName: "SearchPage" */ "@/views/SearchPage.vue"),
      },
      {
        // 会匹配所有路径：https://router.vuejs.org/zh/guide/essentials/dynamic-matching.html#%E6%8D%95%E8%8E%B7%E6%89%80%E6%9C%89%E8%B7%AF%E7%94%B1%E6%88%96-404-not-found-%E8%B7%AF%E7%94%B1
        path: "/:pathMatch(.*)*",
        name: "Page404",
        component: () =>
          import(/* webpackChunkName: "Page404" */ "@/views/Page404.vue"),
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach((to) => {
  const isLogin = localStorage.getItem("isLogin");
  debugger;
  if ("Login" === to.name) {
    if (isLogin) {
      // 这里可认为是回强制回到首页
      return { name: "SearchPage" };
    } else {
      // 继续转入登录页
      return true;
    }
  } else if ("Page404" === to.name) {
    // 404路由则允许继续访问
    return true;
  }
  if (isLogin) {
    // 已登录，则允许继续访问
    return true;
  } else {
    // 未登录，则强制转入登录界面
    return { name: "Login" };
  }
});

export default router;
